package net.begincode.SSO.handler;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import net.begincode.SSO.bean.SsoUser;
import net.begincode.SSO.bean.Url;
import net.begincode.SSO.enums.UserResponse;
import net.begincode.SSO.exception.UserException;
import net.begincode.SSO.service.UserService;
import net.begincode.SSO.util.JedisUtil;
import net.begincode.SSO.util.MD5Utils;

/**
 * 逻辑层
 * @author 遗忘
 * @date 2017.6.1
 */
@Component
public class UserHandler {
	@Resource
	private UserService service;
	
	private Logger logger = LoggerFactory.getLogger("user");
	/**
	 * 用户注册，
	 * openId为空时代表普通注册，反之为第三方注册
	 * @param user
	 * @throws UserException 
	 */
	public int regist(SsoUser user) throws UserException{
		if(user==null){
			logger.info("用户注册参数不能为空");
			throw new UserException(UserResponse.REGIST_USER_ERROR.getMessage());
		}
		if(user.getOpenId()!=null){
			return authThirdParty(user);
		}
		if(user.getEmail()==null||user.getPassword()==null){
			logger.info("用户注册参数不能为空");
			throw new UserException(UserResponse.REGIST_USER_ERROR.getMessage());
		}
		
		if(user.getEmail()!=null){
			if(existUsername(user.getEmail())){
				logger.info("该邮箱已被注册");
				throw new UserException(UserResponse.EMAILEXIST_ERROR.getMessage());
			}
		}
		user.setDeleteFlag(false);
		user.setRole(0);
		user.setVerify(false);
		user.setPassword(MD5Utils.md5(user.getPassword()));
		service.addUser(user);
		return 1;
	}
	
	public boolean existUsername(String email){
		if(service.findUserByEmail(email)!=null){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 第三方登录保存信息
	 * @param user
	 * @throws UserException 
	 */
	public int authThirdParty(SsoUser user) throws UserException{
		if(service.findUserByOpenId(user.getOpenId())!=null){
			logger.info("该用户已保存信息，无需再次保存");
			return 2;
		}
		user.setDeleteFlag(false);
		user.setVerify(false);
		user.setEmail("");
		user.setRole(0);
		user.setPassword("");
		service.addUser(user);
		return 2;
		
	}
	
	/**
	 * 用户登录
	 * @param loginUser
	 * @throws UserException
	 */
	public SsoUser login(SsoUser loginUser) throws UserException{
		if(loginUser==null||loginUser.getEmail()==null){
			logger.info("登录的用户信息不能为空");
			throw new UserException(UserResponse.LOGIN_USER_ERROR.getMessage());
		}
		SsoUser user = service.findUserByEmail(loginUser.getEmail());
		if(user==null||!user.getPassword().equals(MD5Utils.md5(loginUser.getPassword()))){
			logger.info("用户名或密码错误");
			throw new UserException(UserResponse.USERNAME_OR_PASSWORD_ERROR.getMessage());
		}else{
			return user;
		}
	}
	
	/**
	 * 模拟全局session 存储数据到redis中
	 * 使用UUID作为唯一标识
	 * @return
	 */
	public String intoRedis(){
		UUID uuid = UUID.randomUUID(); 
		
		String key = uuid.toString();
		Set<String> set = new HashSet<String>();
		set.add("none");
		JedisUtil.setSet(key,set,60*30);
		JedisUtil.close();
		return key;
	}
	
	/**
	 * 验证登录状态
	 * @param url
	 * @return
	 */
	public boolean verifyLoginState(Url url){
		if(JedisUtil.existsKey(url.getTicket())){
			JedisUtil.setSet(url.getTicket(), url.getLogoutURL(), 60*30);
			JedisUtil.close();
			return true;
		}else{
			JedisUtil.close();
			return false;
		}
	}


	/**
	 * 通知所有子系统注销，删除redis中的ticket
	 * @param key
	 */
	public String logoutAll(String key) {
		if(key==null||"".equals(key)){
			logger.warn("无效值，未登录或ticket出错");
			return "none";
		}
		List<String> urlList = new ArrayList<String>(JedisUtil.getSet(key));
		 if(urlList.size()<=1){
		    	JedisUtil.removeKey(key);
		    }
		JedisUtil.delSetValue(key,urlList.get(0));
		JedisUtil.close();
	    return  urlList.get(0);
	}
	
	
	
}
